package com.tool4j.util;

import cn.hutool.json.JSONUtil;
import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.sdk.service.dysmsapi20170525.AsyncClient;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsResponseBody;
import darabonba.core.client.ClientOverrideConfiguration;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

@Slf4j
public class SendSmsUtil {

    private static String accessKey = "LTAI5tM7qvmhempZVToa2EZB";
    private static String accessKeySecret = "AENmk00v8WrjZhlPOy8j48tvjUl4kv";

    public static void sendVerifyCode(String phoneNum, String verifyCode) {
        log.info("\n>>>>>>>>>>>>>> 发送短信验证码, phoneNum = {}, verifyCode = {}", phoneNum, verifyCode);
        StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
                .accessKeyId(accessKey)
                .accessKeySecret(accessKeySecret)
                .build());
        try (AsyncClient client = AsyncClient.builder()
                .region("cn-hangzhou")
                .credentialsProvider(provider)
                .overrideConfiguration(
                        ClientOverrideConfiguration.create()
                                .setEndpointOverride("dysmsapi.aliyuncs.com")
                )
                .build()) {
            Map<String, Object> templateParam = new HashMap<>();
            templateParam.put("code", verifyCode);
            SendSmsRequest sendSmsRequest = SendSmsRequest.builder()
                    .signName("tool4j")
                    .templateCode("SMS_463760855")
                    .templateParam(JSONUtil.toJsonStr(templateParam))
                    .phoneNumbers(phoneNum)
                    .build();
            CompletableFuture<SendSmsResponse> response = client.sendSms(sendSmsRequest);
            SendSmsResponse resp = response.get();
            SendSmsResponseBody body = resp.getBody();
            log.info(">>>>>>>>>>>>>> 发送短信验证码,响应：{}", JSONUtil.toJsonStr(body));
        } catch (Exception e) {
            log.error("\n>>>>>>>>>>>>>> 验证码发送失败", e);
        }
    }

}